package com.fh.modules.system.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.util.IOUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.api.vo.Result;
import com.fh.common.aspect.annotation.AutoLog;
import com.fh.common.constant.CommonConstant;
import com.fh.common.exception.SelfDefinedException;
import com.fh.common.query.QueryWrapperUtil;
import com.fh.common.web.AbstractController;
import com.fh.modules.system.entity.SysFile;
import com.fh.modules.system.service.ISysFileCategoryService;
import com.fh.modules.system.service.ISysFileService;
import com.fh.modules.system.vo.SysFileVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Qiu,Junda 
 * @date 2019年4月17日
 * @description 文件上传下载controller
 */
@RestController
@RequestMapping("/system/sysFile")
@Api("文件上传下载")
public class SysFileController extends AbstractController{
	
	@Value(value = "${fh.path.upload}")
	private String uploadpath;
	
	@Autowired
	private ISysFileService sysFileService;
	
	@Autowired
	private ISysFileCategoryService sysFileCategoryService;
	
	/**
	  * 分页列表查询
	 * @param sysFile
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	@ApiOperation("分页列表查询")
	@AutoLog(value="上传文件记录分页查询",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result<IPage<SysFile>> queryPageList(SysFile sysFile,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<SysFile>> result = new Result<IPage<SysFile>>();
		QueryWrapper<SysFile> queryWrapper = new QueryWrapper<SysFile>();
		QueryWrapperUtil.initQueryWrapper(queryWrapper, sysFile);
		Page<SysFile> page = new Page<SysFile>(pageNo, pageSize);
		IPage<SysFile> pageList = sysFileService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	@ApiOperation("通过id删除")
	@AutoLog("删除上传附件")
	public Result delete(@RequestParam(name="id",required=true) String id) {
		sysFileService.deleteEntityByDelFlag(id);
		return Result.ok("删除成功");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	@ApiOperation("批量删除")
	@AutoLog("批量删除上传附件")
	public Result deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		sysFileService.deleteBatchEntityByDelFlag(ids);
		return Result.ok("批量删除成功");
	}
	
	@ApiOperation("单个文件上传接口")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result upload(String categoryId,String tag,String description,
			@RequestParam("file")MultipartFile multipartFile){
		//----------文件上传
		
		String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
		File file = new File(uploadpath + File.separator + nowday);
		if (!file.exists()) {
			file.mkdirs();// 创建文件根目录
		}
		String fileName = null;
		Long fileSize=multipartFile.getSize();
		// 获取文件名
		String originalName = multipartFile.getOriginalFilename();
		//文件后缀
		String suffix=originalName.substring(originalName.indexOf("."));
		fileName = originalName.substring(0, originalName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + suffix;
		String savePath = file.getPath() + File.separator + fileName;
		File savefile = new File(savePath);
		try {
			FileCopyUtils.copy(multipartFile.getBytes(), savefile);
		} catch (IOException e) {
			throw new SelfDefinedException("文件上传失败"+e.getMessage());
		}
		//----------文件上传
		
		//保存上传记录
		SysFile sysFile=new SysFile();
		sysFile.setCategoryId(categoryId);sysFile.setDescription(description);sysFile.setTag(tag);
		sysFile.setName(originalName);sysFile.setSuffix(suffix);sysFile.setLocalUrl(savePath);
		sysFile.setSize(fileSize.intValue());
		sysFileService.save(sysFile);
		//保存上传记录
		return Result.ok(sysFile);
	}
	
	@ApiOperation("多文件上传接口")
	@PostMapping(value = "/uploadMultis", consumes="multipart/*" ,headers="content-type=multipart/form-data")
	public Result uploadMultis(@ApiParam(value="上传的文件",required=true) MultipartFile[] multipartFiles) {
		String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
		File file = new File(uploadpath + File.separator + nowday);
		if (!file.exists()) {
			file.mkdirs();// 创建文件根目录
		}
		for(int i=0;i<multipartFiles.length;i++) {
			MultipartFile multipartFile=multipartFiles[i];
			String fileName = null;
			Long fileSize=multipartFile.getSize();
			// 获取文件名
			String originalName = multipartFile.getOriginalFilename();
			//文件后缀
			String suffix=originalName.substring(originalName.indexOf("."));
			fileName = originalName.substring(0, originalName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + suffix;
			String savePath = file.getPath() + File.separator + fileName;
			File savefile = new File(savePath);
			try {
				FileCopyUtils.copy(multipartFile.getBytes(), savefile);
			} catch (IOException e) {
				throw new SelfDefinedException("文件上传失败"+e.getMessage());
			}
			//----------文件上传
			
			//保存上传记录
			SysFile sysFile=new SysFile();
			sysFile.setName(originalName);sysFile.setSuffix(suffix);sysFile.setLocalUrl(savePath);
			sysFile.setSize(fileSize.intValue());
			sysFileService.save(sysFile);
		}
		
		return Result.ok("上传成功");
	}
	
	@GetMapping(value = "/download/{id}")
	public void download(@PathVariable String id,HttpServletRequest request, HttpServletResponse response) {
		SysFile sysFile=sysFileService.getById(id);
		sysFileService.addFileDownloadTimes(sysFile);
		// ISO-8859-1 ==> UTF-8 进行编码转换
		String filePath = sysFile.getLocalUrl();
		// 其余处理略
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename="+sysFile.getName());
			String localPath = uploadpath;
			String fileUrl = localPath + File.separator + filePath;
			inputStream = new BufferedInputStream(new FileInputStream(fileUrl));
			outputStream = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, len);
			}
			response.flushBuffer();
		} catch (IOException e) {
			log.info("下载文件失败：" + e.getMessage());
		} finally {
			IOUtils.close(inputStream);
			IOUtils.close(outputStream);
		}

	}
	
	/**
	 * 当前登录用户分页查询附件上传记录
	 */
	@RequestMapping(value="/queryUploadPageList" ,method=RequestMethod.GET)
	@ApiOperation("当前登录用户分页查询附件上传记录")
	@AutoLog(value="当前登录用户分页查询上传附件",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result queryUploadPageList(SysFileVo fileVo) {
		return Result.okPage(sysFileService.queryFilePage(fileVo));
	}
	/**
	 * 查询所有文件目录分类
	 * @author Qiu,Junda
	 * @date 2019年5月14日
	 */
	@GetMapping("/queryAllFileCategory")
	@AutoLog(value="查询文件目录分类",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result queryAllFileCategory() {
		return Result.ok(sysFileCategoryService.queryFileCategory());
	}
	/**
	 * 查询所有附件上传记录
	 */
	@RequestMapping(value="/queryAllUploadPageList" ,method=RequestMethod.GET)
	@ApiOperation("查询所有附件上传记录")
	
	public Result queryAllUploadPageList(SysFileVo fileVo) {
		
		return Result.ok("");
	}
	
	/**
	 * 分页查询附件下载记录,文件id
	 */
	@RequestMapping(value="/queryDownloadPageList" ,method=RequestMethod.GET)
	@ApiOperation("分页查询附件下载记录,文件id")
	public Result queryDownloadPageList(String id) {
		
		return Result.ok("");
	}
	
	/**
	 * 删除文件上传记录 ids逗号分隔
	 */
	@RequestMapping(value="/deleteUpload" ,method=RequestMethod.GET)
	@ApiOperation("删除文件上传记录 ids逗号分隔")
	public Result deleteUpload(String ids) {
		
		return Result.ok("");
	}

}
